<template>
    <div class="container flex-col">
        <div class="flex-row space-between">
            <span class="page_title">问卷编辑</span>
            <div>
                <el-button @click="btn_click_create_qt" class="btn_top" type="primary"
                           style="background-color: #3F8CFF ;color: white;">
                    <img src="@/assets/edit.png" alt="下载" class="img_in_btn">
                    <span class="txt_in_btn" style="color: white;">新建</span>
                </el-button>
                <el-button class="btn_top" link @click="click_preview">
                    预览
                </el-button>

                <el-button class="btn_top" link @click="click_end_edit">
                    完成编辑
                </el-button>
            </div>
        </div>
        <div class="flex-row flex_1" style="margin-top: 16px; ">
            <div class="comm_border h_full" style="width: 600px;">
                <div class="flex-col h_full" style="margin: auto 16px; ">
                    <div class="flex-row-center" style="margin-top: 16px;">
                        <el-input label="题目" style="height: 40px; width: 200px;" class="search_input"></el-input>
                        <el-select size="large" style="margin-left: 8px; width: 100px;" v-model="data.qtType"
                                   placeholder="题型">
                            <el-option v-for="(qtType, index) in listQtType"
                                       :key="index"
                                       :label="qtType.value"
                                       :value="qtType.key"></el-option>
                        </el-select>
                        <el-button class="search_btn_primary" type="primary" style="margin-left: 8px; height: 40px; "
                                   @click="click_search">
                            搜索
                        </el-button>
                    </div>

                    <div class="flex_1">
                        <el-table style="margin-top: 16px;" :data="data.listQtBank" border>
                            <el-table-column prop="index" label="序号" width="50" />
                            <el-table-column prop="title" label="题目" />
                            <el-table-column prop="qtTypeStr" label="题型" width="80" />
                            <el-table-column prop="score" label="分值" width="60" />
                            <el-table-column label="操作" width="60">
                                <template #default="scope">
                                    <el-button :icon="Plus" link style="text-align: center"
                                               @click="handleDelete(scope.$index, scope.row)">
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="flex-row-reverse-center" style="height: 50px;">
                        <el-pagination v-model:current-page="pager.currentPage"
                                       v-model:page-size="pager.pageSize"
                                       :page-sizes="[10,20,50,100]"
                                       layout="total, sizes, prev, pager, next, jumper"
                                       :total="pager.total"
                                       @size-change="handleSizeChange"
                                       @current-change="handleCurrentChange"></el-pagination>
                    </div>
                </div>
                <div class="flex_1"></div>
            </div>
            <div class="comm_border flex_1 h_full" style="margin-left: 16px; ">
                <div style="margin: 16px; overflow-y: auto;height: calc(100vh - 200px); /* 视口高度减去300px */">
                    <div @mouseenter="mouse_enter_div(item)" @mouseleave="mouse_leave_div(item)" style="margin-top: 16px;"
                         v-for="(item,i) in data.listQtInNaire">
                        <div class="flex-col">
                            <span class="qtTitle">{{ item.index }}: {{ item.title }} ({{ item.qtTypeStr }})</span>
                            <div v-if="item.qtType== QtType_Single ||item.qtType==QtType_TrueFalse">
                                <div class="flex-col" style="margin-top: 8px;  " v-for="item_item in item.listItemInfo">
                                    <div class="flex-row-center">
                                        <el-radio class="option">{{ item_item.content }} ({{ item_item.score }}分)</el-radio>
                                    </div>
                                </div>
                            </div>
                            <div v-if="item.qtType== QtType_Multi">
                                <div class="flex-col" style="margin-top: 8px;" v-for="item_item in item.listItemInfo">
                                    <div class="flex-row-center">
                                        <el-checkbox class="option">{{ item_item.content }} ({{ item_item.score }}分)</el-checkbox>
                                    </div>
                                </div>
                            </div>
                            <div class="flex-row-reverse-center" style="height: 30px">
                                <div v-if="item.isShowBtn">
                                    <el-button class="btn_edit" @click="click_item_delete(item,i)" :icon="Delete">删除</el-button>
                                    <el-button class="btn_edit" @click="click_item_up(item,i)" :icon="Top">上移</el-button>
                                    <el-button class="btn_edit" @click="click_item_down(item,i)" :icon="Bottom">下移</el-button>
                                    <el-button class="btn_edit" @click="click_item_top(item,i)" :icon="Upload">置顶</el-button>
                                    <el-button class="btn_edit" @click="click_item_bottom(item,i)" :icon="Download">置底</el-button>
                                </div>
                            </div>
                            <div v-if="i!=data.listQtInNaire.length-1" class="comm_split_h"></div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { Bottom, Delete, Download, Plus, Top, Upload } from "@element-plus/icons-vue";
    import { onMounted, reactive } from "vue";
    import { ExamType_Naire } from "@/constants/Constants_ExamType";
    import { api_question_bank_all, api_question_bank_list } from "@/request/apis/qtApi";
    import { QtBankVO } from "@/type/vo/QtBankVO";
    import { ElMessage } from "element-plus";
    import { addDialog } from "@/components/gDialog/index";
    import { shallowRef } from "vue"
    import QtCreate from "@/views/Naire/dialogs/NaireQtCreate.vue";
    import { tickAsTimeString } from "@/utils/TimeUtil";
    import { ListQtTypeInfo } from "@/constants/Constants_ListQtTypeInfo";
    import { QtType_Multi, QtType_Single, QtType_TrueFalse } from "@/constants/Constants_QtType";
    import { QtTypeAsString } from "@/utils/EnumHelper";
    import { useRoute } from "vue-router";
    import { api_getExamInfo, api_updateExam } from "@/request/apis/examApi";
    import router from "@/router";
    import { ExamVO } from "@/type/vo/ExamVO";
    import NairePreview from "@/views/Naire/dialogs/NairePreview.vue";
    import msg from '@/components/msg'

    const route = useRoute();
    const _examId = route.query.examId as string;
    console.log('route', _examId);
    const data = reactive({
        examId: _examId,
        title: '',
        qtName: '',
        qtType: 0,
        listQtBank: Array<QtBankVO>(),
        listQtInNaire: Array<QtBankVO>(),
    })

    const pager = reactive({
        currentPage: 1,
        pageSize: 10,
        total: 10,
    })
    const listQtType = reactive(ListQtTypeInfo);
    let examVO: ExamVO = {};

    const click_search = () => {
        pager.currentPage = 1;
        search_pri();
    }


    const click_item_delete = (item: QtBankVO, index: number) => {
        if (index > 0) {
            data.listQtInNaire.splice(index, 1);
        }
    }

    const click_item_up = (item: QtBankVO, index: number) => {
        if (index > 0) {
            data.listQtInNaire.splice(index, 1);
            data.listQtInNaire.splice(index - 1, 0, item);
        }

    }
    const click_item_down = (item: QtBankVO, index: number) => {
        if (index + 1 < data.listQtInNaire.length) {
            data.listQtInNaire.splice(index, 1);
            data.listQtInNaire.splice(index + 1, 0, item);
        }
    }

    const click_item_top = (item: QtBankVO, index: number) => {
        if (index > 0) {
            data.listQtInNaire.splice(index, 1);
            data.listQtInNaire.splice(0, 0, item);
        }
    }

    const click_item_bottom = (item: QtBankVO, index: number) => {
        if (index + 1 < data.listQtInNaire.length) {
            data.listQtInNaire.splice(index, 1);
            data.listQtInNaire.push(item);
        }
    }


    const mouse_enter_div = (item: QtBankVO) => {
        item.isShowBtn = true;
    }
    const mouse_leave_div = (item: QtBankVO) => {
        item.isShowBtn = false;
    }

    const handleDelete = async (index: number, row: QtBankVO) => {
        console.log(index, row)
        //检查在右侧有没有
        // if (data.listQtInNaire.some((item) => item.qbId == row.qbId)) {
        //   await msg.info('当前题目已经存在问卷中!');
        //   return;
        // }
        //先去请求
        const r = await api_question_bank_all(row.qbId);
        if (!r) {
            await msg.info('获取题目 数据异常', '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        if (r.code != 0) {
            await msg.info(`获取题目 数据异常!  ${r.code} msg：${r.msg}`, '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        r.data.index = data.listQtInNaire.length + 1;
        r.data.qtTypeStr = QtTypeAsString(r.data.qtType);
        data.listQtInNaire.push(r.data);
    }

    onMounted(async () => {
        await search_qtInNaire();
        await search_pri();
    })
    const search_qtInNaire = async () => {
        console.log('data.examId', data.examId);
        const r = await api_getExamInfo(data.examId);
        if (!r) {
            await msg.info('获取问卷数据异常', '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        if (r.code != 0) {
            await msg.info(`获取问卷 数据异常!  ${r.code} msg：${r.msg}`, '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        examVO = r.data;
        data.listQtInNaire.length = 0;
        if (r.data.listHistoryQuestion) {
            r.data.listHistoryQuestion.forEach(x => {
                x.index = data.listQtInNaire.length + 1;
                x.createTimeStr = tickAsTimeString(x.createTime)
                x.qtTypeStr = QtTypeAsString(x.qtType)
                data.listQtInNaire.push(x);
            });
        }
    }

    const click_preview = () => {
        try {

            addDialog({
                title: "问卷预览",
                component: shallowRef(NairePreview),
                width: "600px",
                props: {
                    title: examVO.title,
                    listQtInNaire: data.listQtInNaire
                },
                callBack: (dRet: boolean) => {
                }
            })
            // 处理确认操作
        } catch (error) {
            // 处理取消操作
        }
    }
    const click_end_edit = async () => {
        examVO.listQbId = [];
        data.listQtInNaire.forEach(x => {
            examVO.listQbId.push(x.qbId);
        })
        const r = await api_updateExam(examVO);
        if (!r) {
            await msg.info('数据异常', '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        if (r.code != 0) {
            await msg.info(`数据异常!  ${r.code} msg：${r.msg}`, '提示', {
                confirmButtonText: '确定'
            });
            return;
        }
        //调回页面
        await router.push({
            path: '/naireList'
        })
    }
    const handleSizeChange = (val: number) => {
        console.log(`${val} items per page`)
        search_pri();
    }


    const search_pri = async () => {
        data.listQtBank.length = 0;
        const startDate = null;
        const questionTag = '';
        const endDate = null;
        const page = pager.currentPage;
        const limit = pager.pageSize;
        const examType = ExamType_Naire;
        const questionName = data.qtName;
        let queryType = 0;
        if (data.qtType > 0) {
            queryType = data.qtType;
        }
        const r = await api_question_bank_list(startDate,
            endDate,
            questionName,
            questionTag,
            queryType,
            examType, page, limit);
        if (!r) {
            await msg.error('数据异常!');
            return;
        }
        if (r.code != 0) {
            await msg.error(`错误! ${r.code}${r.msg}`);
            return;
        }
        if (r.data.records) {
            for (let i = 0; i < r.data.records.length; i++) {
                r.data.records[i].index = i + 1;
                r.data.records[i].createTimeStr = tickAsTimeString(r.data.records[i].createTime)
                r.data.records[i].qtTypeStr = QtTypeAsString(r.data.records[i].qtType)
            }
        }

        data.listQtBank = r.data.records;
        pager.total = r.data.total;
    }

    const handleCurrentChange = (val: number) => {
        search_pri();
    }

    interface User {
        date: string
        name: string
        address: string
    }


    async function btn_click_create_qt() {
        try {
            addDialog({
                title: "创建题目",
                component: shallowRef(QtCreate),
                width: "600px",
                props: {},
                callBack: async (goEdit: Boolean) => {
                    if (goEdit) {
                        ElMessage.success('创建成功!');
                        await search_pri();
                    } else {
                        // tableList.data[index as number] = data
                    }
                    console.log(data, "data")
                }
            })
            // 处理确认操作
        } catch (error) {
            // 处理取消操作
        }
    }
</script>

<style scoped>
    .btn_top {
        border: none;
        height: 48px;
        padding: 13px 28px;
        background-color: white;
        border-radius: 12px;
        color: #3F8CFF;
        font-size: 16px;
        font-weight: 400;
    }


    .el-table .warning-row {
        --el-table-tr-bg-color: var(--el-color-warning-light-9);
    }

    .el-table .success-row {
        --el-table-tr-bg-color: var(--el-color-success-light-9);
    }

    .qtTitle {
        font-size: 20px;
        font-weight: 400;
        color: #0A1629;
        line-height: 24px;
    }

    .option {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
        line-height: 22px;
    }

    .btn_edit {
        height: 24px;
        font-size: 12px;
        font-weight: 400;
        color: #91929E;
        line-height: 20px;
        padding: 2px 8px;
        border-radius: 3px 3px 3px 3px;
        border: 1px solid #91929E;
    }
</style>